/**
 * Copyright (C), 2020-2020, 软件公司
 * FileName: ProducerTest1
 * Author:   cakin
 * Date:     2020/5/7
 * Description: immediate的测试
 */
package com.rabbitmq.msgdirection.immediate;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.MessageProperties;
import com.rabbitmq.client.ReturnListener;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.util.ConnectionUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import static com.rabbitmq.common.Constant.NUM3;

/**
 * @ClassName: ProducerTest
 * @Description: immediate的测试
 * @Date: 2020/5/7
 * @Author: cakin
 */
@Slf4j
public class ProducerTest {
    public static void main( String[] args ) {
        String exchangeName = "confirmExchange";
        String routingKey = "confirmRoutingKey";
        int count = NUM3;

        // 获取连接
        try {
            Connection connection = ConnectionUtils.getConnection();
            Channel channel = connection.createChannel();
            // 创建exchange
            channel.exchangeDeclare(exchangeName, "direct", true, false, null);
            // 发送持久化消息
            for (int i = 0; i < count; i++) {
                /**
                 *  exchangeName:默认情况下代理服务器端是存在一个""名字的exchange的,
                 *  因此如果不创建exchange的话我们可以直接将该参数设置成"",
                 *  如果创建了exchange的话我们需要将该参数设置成创建的exchange的名字
                 *  routingKey:路由键
                 *  mandatory:true 表示如果没有路由会返回
                 *  immediate:官方不再支持
                 *  启用该参数，会报错
                 *  WARN com.rabbitmq.client.impl.ForgivingExceptionHandler -
                 *  An unexpected connection driver error occured (Exception message: Connection reset)
                 */
                channel.basicPublish(exchangeName, routingKey, true, true,
                        MessageProperties.PERSISTENT_BASIC, ("第" + (i + 1) + "条消息").getBytes());
            }

            channel.addReturnListener(new ReturnListener() {

                @Override
                public void handleReturn( int replyCode, String replyText, String exchange, String routingKey,
                                          AMQP.BasicProperties properties, byte[] body ) throws IOException {
                    //此处便是执行Basic.Return之后回调的地方
                    String message = new String(body);
                    System.out.println("Basic.Return返回的结果:  " + message);
                }
            });

        } catch (IOException e) {
            log.info("catch IOException");
        } catch (TimeoutException e) {
            log.info("catch TimeoutException");
        }
    }
}

